
/**
 * 场景管理API接口
 */

import axios from 'axios'

// 基础配置 - 统一使用vite代理配置
const API_BASE_URL = '/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token等
    console.log('API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log('API Response:', response.status, response.config.url)
    return response.data  // 直接返回数据，而不是完整的response对象
  },
  (error) => {
    console.error('Response Error:', error.response?.status, error.config?.url)
    return Promise.reject(error)
  }
)

// 工具函数：过滤空值参数
const filterEmptyParams = (params?: any) => {
  if (!params || typeof params !== 'object') return {}
  const filtered: any = {}
  Object.entries(params).forEach(([key, value]) => {
    if (value !== '' && value !== null && value !== undefined) {
      filtered[key] = value
    }
  })
  return filtered
}

// 类型定义
export interface SceneStatus {
  ACTIVE: 'active'
  INACTIVE: 'inactive'
  PENDING_REVIEW: 'pending_review'
  ARCHIVED: 'archived'
}

export interface AIWebScene {
  scene_id: string
  scene_name: string
  description?: string
  parent_id?: string
  node_path?: string
  node_level: number
  sort_order: number
  scene_status: string
  creator: string
  create_time: string
  modifier?: string
  modify_time?: string
  version: number
  children?: AIWebScene[]
}

export interface SceneTreeResponse {
  total_count: number
  max_depth: number
  root_nodes: AIWebScene[]
}

export interface SearchForm {
  scene_name?: string
  scene_status?: string
  creator?: string
  include_children: boolean
  max_depth?: number
}

export interface CreateSceneRequest {
  scene_name: string
  description?: string
  parent_id?: string
  sort_order: number
  scene_status: string
  creator: string
}

export interface UpdateSceneRequest {
  scene_name?: string
  description?: string
  sort_order?: number
  scene_status?: string
  modifier: string
  version: number
}

export interface MoveSceneRequest {
  new_parent_id?: string
}

// 场景相关API
export const sceneApi = {
  // 获取场景树
  getSceneTree: (params?: any): Promise<SceneTreeResponse> => apiClient.get('/scene/tree', { params: filterEmptyParams(params) }),
  
  // 获取场景选项（下拉框用）
  getSceneOptions: (params?: any): Promise<any[]> => apiClient.get('/scene/options', { params: filterEmptyParams(params) }),
  
  // 根据ID获取场景
  getSceneById: (sceneId: string): Promise<AIWebScene> => apiClient.get(`/scene/${sceneId}`),
  
  // 创建场景
  createScene: (data: any): Promise<AIWebScene> => apiClient.post('/scene/', data),
  
  // 更新场景
  updateScene: (sceneId: string, data: any): Promise<AIWebScene> => apiClient.put(`/scene/${sceneId}`, data),
  
  // 删除场景
  deleteScene: (sceneId: string): Promise<any> => apiClient.delete(`/scene/${sceneId}`),
  
  // 移动场景
  moveScene: (sceneId: string, newParentId?: string): Promise<AIWebScene> => 
    apiClient.post(`/scene/${sceneId}/move`, { new_parent_id: newParentId }),

  // 获取子场景列表
  getChildren: (parentId: string): Promise<AIWebScene[]> => apiClient.get(`/scene/${parentId}/children`),

  // 获取场景路径
  getScenePath: (sceneId: string): Promise<AIWebScene[]> => apiClient.get(`/scene/${sceneId}/path`),

  // 获取祖先节点
  getAncestors: (sceneId: string): Promise<AIWebScene[]> => apiClient.get(`/scene/${sceneId}/ancestors`),

  // 获取后代节点
  getDescendants: (sceneId: string): Promise<AIWebScene[]> => apiClient.get(`/scene/${sceneId}/descendants`),

  // 获取所有场景（扁平列表）
  getAllScenes: (sceneStatus?: string): Promise<AIWebScene[]> => {
    const params: any = {}
    if (sceneStatus && sceneStatus !== '') params.scene_status = sceneStatus
    return apiClient.get('/scene/', { params })
  }
}

// 对话框相关API
export const dialogApi = {
  // 获取对话框列表
  getDialogs: (params?: any): Promise<{dialogs: any[], total_count: number}> => apiClient.get('/dialog/', { params: filterEmptyParams(params) }),
  
  // 根据ID获取对话框
  getDialogById: (dialogId: number): Promise<any> => apiClient.get(`/dialog/${dialogId}`),
  
  // 根据场景ID获取对话框
  getDialogByScene: (sceneId: string): Promise<any> => apiClient.get(`/dialog/scene/${sceneId}`),
  
  // 创建对话框
  createDialog: (data: any): Promise<any> => apiClient.post('/dialog/', data),
  
  // 更新对话框
  updateDialog: (dialogId: number, data: any): Promise<any> => apiClient.put(`/dialog/${dialogId}`, data),
  
  // 删除对话框
  deleteDialog: (dialogId: number): Promise<any> => apiClient.delete(`/dialog/${dialogId}`),
  
  // 动态调整对话框大小
  updateDialogSize: (dialogId: number, size: any): Promise<any> => 
    apiClient.put(`/dialog/${dialogId}/size`, size),
  
  // 动态调整交互模式
  updateDialogInteractive: (dialogId: number, params: any): Promise<any> => 
    apiClient.put(`/dialog/${dialogId}/interactive`, null, { params }),
  
  // 动态调整透明度
  updateDialogTransparency: (dialogId: number, transparency: number): Promise<any> => 
    apiClient.put(`/dialog/${dialogId}/transparency`, null, { params: { transparency } }),
  
  // 编码交互模式
  encodeInteractiveModes: (params: any): Promise<any> => apiClient.get('/dialog/modes/encode', { params }),
  
  // 解码交互模式
  decodeInteractiveModes: (value: number): Promise<any> => apiClient.get(`/dialog/modes/decode/${value}`)
}

export default apiClient 